/*
License:
	MIT-style license

Author:
	Jan Kassens
	
Dependencies:
	Mootools >= 1.2dev
	Remote.XHR and Remote.Json
*/
var MooRemote = new Class({

	initialize: function(functions, options){
		this.$options = $merge({
			'url': undefined
		}, options);
		var self = this;
		functions.each(function(fn){
			if(fn.class){
				self[fn.class] = {};
				fn.methods.each(function(method){
					self[fn.class][method] = function(){
						return new MooRequest(self.$options.url, [fn.class, method], $A(arguments));
					}
				});
			} else {
				self[fn] = function(){
					return new MooRequest(self.$options.url, fn, $A(arguments));
				}
			};
		});
	}

});

var MooRequest = XHR.extend({

	initialize: function(url, fn, params){
		this.parent();
		this.setHeader('X-Requested-With', 'MooRequest');
		this.send(url || window.location.href, "call=" + encodeURIComponent(Json.encode({'method': fn, 'params': params})));
		if(window.console) this.addEvent("onError", function(error){console.error(error)});
	},

	onSuccess: function(){
		var response = Json.decode(this.transport.responseText);
		if($defined(response.script)) window.execScript ? window.execScript(response.script) : window.setTimeout(response.script, 0);
		if($defined(response.error)) this.fireEvent('onError', response.error);
		else this.fireEvent('onSuccess', $defined(response.result) ? [response.result] : []);
	},

	callback: function(fn){
		return this.addEvent('onSuccess', fn);
	}

});